package com.block.common.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.block.common.service.IChannelCommonService;
import com.block.db.entity.ChannelInfo;
import com.block.db.mapper.ChannelInfoMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class ChannelCommonServcie implements IChannelCommonService {

    private  static  final  String CHANNEL_INFO_KEY_PREFIX="CHANNEL:INFO:CODE:";
    private  static  final  Long CHANNEL_INFO_KEY_TIME_OUT=4L;

    @Resource
    ChannelInfoMapper channelInfoMapper;
    @Resource
    private RedisTemplate<String, ChannelInfo> redisChannelInfoTemplate;

    @Override
    public ChannelInfo getChannelInfoCache(String channelCode){
        String redisKey = CHANNEL_INFO_KEY_PREFIX+channelCode;
        ChannelInfo channelInfo= redisChannelInfoTemplate.opsForValue().get(redisKey);
        if(ObjectUtil.isEmpty(channelInfo)){
            channelInfo = this.channelInfoMapper.getBaseInfoByCode(channelCode);
            if(channelInfo!=null) {
                redisChannelInfoTemplate.opsForValue().set(redisKey, channelInfo, CHANNEL_INFO_KEY_TIME_OUT, TimeUnit.HOURS);
            }
        }
        return channelInfo;
    }
}
